<template>
  <div class="app-container">
    <div v-if="loading" class="loading-container">
      <el-loading text="正在生成您的测试结果..."></el-loading>
    </div>

    <div v-else-if="result" class="result-container">
      <!-- 结果标题 -->
      <div class="result-header">
        <h1 class="personality-type">{{ result.personalityType }}</h1>
        <h2 class="type-name">{{ result.typeName }}</h2>
        <p class="type-nickname" v-if="result.typeNickname">{{ result.typeNickname }}</p>
        <div class="share-buttons">
          <el-button type="primary" @click="shareResult">
            <el-icon><Share /></el-icon>
            分享结果
          </el-button>
          <el-button @click="downloadResult">
            <el-icon><Download /></el-icon>
            下载报告
          </el-button>
          <el-button @click="retakeTest">
            <el-icon><Refresh /></el-icon>
            重新测试
          </el-button>
        </div>
      </div>

      <!-- 人格类型描述 -->
      <div class="description-section">
        <el-card>
          <template #header>
            <h3><el-icon><User /></el-icon> 人格类型描述</h3>
          </template>
          <p class="description-text">{{ result.description }}</p>
        </el-card>
      </div>

      <!-- 维度得分 -->
      <div class="scores-section">
        <el-card>
          <template #header>
            <h3><el-icon><DataAnalysis /></el-icon> 维度分析</h3>
          </template>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" v-for="dimension in dimensionScores" :key="dimension.name">
              <div class="dimension-score">
                <div class="dimension-header">
                  <span class="dimension-name">{{ dimension.name }}</span>
                  <span class="dimension-percentage">{{ dimension.percentage }}%</span>
                </div>
                <el-progress 
                  :percentage="dimension.percentage" 
                  :color="dimension.color"
                  :stroke-width="12"
                ></el-progress>
                <div class="dimension-description">
                  <strong>{{ dimension.dominant }}</strong> 倾向
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 优势特点 -->
      <div class="strengths-section" v-if="result.strengths">
        <el-card>
          <template #header>
            <h3><el-icon><StarFilled /></el-icon> 优势特点</h3>
          </template>
          <div class="content-text" v-html="formatText(result.strengths)"></div>
        </el-card>
      </div>

      <!-- 发展建议 -->
      <div class="weaknesses-section" v-if="result.weaknesses">
        <el-card>
          <template #header>
            <h3><el-icon><Warning /></el-icon> 发展建议</h3>
          </template>
          <div class="content-text" v-html="formatText(result.weaknesses)"></div>
        </el-card>
      </div>

      <!-- 职业建议 -->
      <div class="career-section" v-if="result.careerSuggestions">
        <el-card>
          <template #header>
            <h3><el-icon><Suitcase /></el-icon> 职业建议</h3>
          </template>
          <div class="content-text" v-html="formatText(result.careerSuggestions)"></div>
        </el-card>
      </div>

      <!-- 人际关系建议 -->
      <div class="relationship-section" v-if="result.relationshipTips">
        <el-card>
          <template #header>
            <h3><el-icon><UserFilled /></el-icon> 人际关系建议</h3>
          </template>
          <div class="content-text" v-html="formatText(result.relationshipTips)"></div>
        </el-card>
      </div>

      <!-- 著名人物 -->
      <div class="famous-people-section" v-if="result.famousPeople">
        <el-card>
          <template #header>
            <h3><el-icon><Trophy /></el-icon> 同类型著名人物</h3>
          </template>
          <div class="content-text" v-html="formatText(result.famousPeople)"></div>
        </el-card>
      </div>

      <!-- 人群占比 -->
      <div class="percentage-section" v-if="result.percentage">
        <el-card>
          <template #header>
            <h3><el-icon><PieChart /></el-icon> 人群分布</h3>
          </template>
          <div class="percentage-content">
            <div class="percentage-chart">
              <el-progress 
                type="circle" 
                :percentage="parseFloat(result.percentage)" 
                :width="120"
                :stroke-width="8"
                color="#409EFF"
              ></el-progress>
            </div>
            <div class="percentage-text">
              <p>在总人群中，{{ result.personalityType }} 类型约占 <strong>{{ result.percentage }}%</strong></p>
              <p>您属于相对{{ parseFloat(result.percentage) > 10 ? '常见' : '稀少' }}的人格类型</p>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 腾讯广告区域 -->
      <div class="tencent-ad-section" v-if="!hasClickedAd">
        <el-card>
          <template #header>
            <h3><el-icon><Present /></el-icon> 解锁完整测试结果</h3>
          </template>
          <div class="ad-content">
            <div class="ad-description">
              <p>点击下方广告即可解锁完整的测试结果保存功能</p>
              <p class="ad-hint">广告内容由腾讯广告主提供，感谢您的支持！</p>
            </div>
            
            <!-- 腾讯广告位 -->
            <div class="tencent-ad-container" id="tencent-ad-container">
              <div class="ad-placeholder" v-if="!adLoaded">
                <el-skeleton :rows="3" animated />
                <p class="loading-text">广告加载中...</p>
              </div>
              <!-- 广告将在这里动态插入 -->
            </div>
            
            <div class="ad-actions">
              <el-button type="primary" size="large" @click="handleAdClick" :disabled="!adLoaded">
                <el-icon><Star /></el-icon>
                点击广告解锁保存功能
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 登录保存提示（仅未登录用户且已点击广告后可见） -->
      <div class="login-save-section" v-if="!isLoggedIn && hasClickedAd">
        <el-alert
          title="保存测试结果"
          type="success"
          description="感谢您的支持！现在您可以登录保存测试结果到个人历史记录。"
          show-icon
          :closable="false"
        >
          <template #default>
            <div class="alert-actions">
              <el-button type="primary" @click="goToLoginWithSave">
                <el-icon><User /></el-icon>
                登录保存结果
              </el-button>
              <el-button @click="dismissSavePrompt">
                暂不保存
              </el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 操作按钮 -->
      <div class="action-section">
        <el-button type="primary" size="large" @click="retakeTest">
          <el-icon><Refresh /></el-icon>
          重新测试
        </el-button>
        <el-button size="large" @click="goHome">
          <el-icon><House /></el-icon>
          返回首页
        </el-button>
        <el-button size="large" @click="viewHistory" v-if="isLoggedIn">
          <el-icon><Document /></el-icon>
          查看历史
        </el-button>
      </div>
    </div>

    <div v-else class="error-container">
      <el-result
        icon="error"
        title="获取结果失败"
        sub-title="无法获取测试结果，请重试"
      >
        <template #extra>
          <el-button type="primary" @click="goHome">返回首页</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { getTestResult } from "@/api/mbti/test"
import { ElMessage } from 'element-plus'
import { 
  Share, Download, Refresh, User, DataAnalysis, StarFilled, Warning, 
  Suitcase, UserFilled, Trophy, PieChart, House, Document, Present, Star 
} from '@element-plus/icons-vue'
import { 
  TENCENT_AD_CONFIG, 
  getAdConfig, 
  checkAdClickStatus as checkAdStatus, 
  saveAdClickRecord, 
  reportAdClick,
  reportAdImpression 
} from '@/config/tencent-ad'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const result = ref(null)
const recordId = ref(null)
const isLoggedIn = ref(false)
const hasClickedAd = ref(false)
const adLoaded = ref(false)
const tencentAd = ref(null)

// 计算属性
const dimensionScores = computed(() => {
  if (!result.value || !result.value.scores) return []
  
  const scores = result.value.scores
  const dimensions = []
  
  // E vs I
  const eScore = scores.E || 0
  const iScore = scores.I || 0
  const eiTotal = eScore + iScore
  if (eiTotal > 0) {
    const ePercentage = Math.round((eScore / eiTotal) * 100)
    dimensions.push({
      name: ePercentage >= 50 ? '外向性 (E)' : '内向性 (I)',
      percentage: Math.max(ePercentage, 100 - ePercentage),
      dominant: ePercentage >= 50 ? '外向' : '内向',
      color: ePercentage >= 50 ? '#409EFF' : '#67C23A'
    })
  }
  
  // S vs N
  const sScore = scores.S || 0
  const nScore = scores.N || 0
  const snTotal = sScore + nScore
  if (snTotal > 0) {
    const sPercentage = Math.round((sScore / snTotal) * 100)
    dimensions.push({
      name: sPercentage >= 50 ? '感觉 (S)' : '直觉 (N)',
      percentage: Math.max(sPercentage, 100 - sPercentage),
      dominant: sPercentage >= 50 ? '感觉' : '直觉',
      color: sPercentage >= 50 ? '#E6A23C' : '#F56C6C'
    })
  }
  
  // T vs F
  const tScore = scores.T || 0
  const fScore = scores.F || 0
  const tfTotal = tScore + fScore
  if (tfTotal > 0) {
    const tPercentage = Math.round((tScore / tfTotal) * 100)
    dimensions.push({
      name: tPercentage >= 50 ? '思考 (T)' : '情感 (F)',
      percentage: Math.max(tPercentage, 100 - tPercentage),
      dominant: tPercentage >= 50 ? '思考' : '情感',
      color: tPercentage >= 50 ? '#909399' : '#9C27B0'
    })
  }
  
  // J vs P
  const jScore = scores.J || 0
  const pScore = scores.P || 0
  const jpTotal = jScore + pScore
  if (jpTotal > 0) {
    const jPercentage = Math.round((jScore / jpTotal) * 100)
    dimensions.push({
      name: jPercentage >= 50 ? '判断 (J)' : '知觉 (P)',
      percentage: Math.max(jPercentage, 100 - jPercentage),
      dominant: jPercentage >= 50 ? '判断' : '知觉',
      color: jPercentage >= 50 ? '#FF9800' : '#4CAF50'
    })
  }
  
  return dimensions
})

// 生命周期
onMounted(() => {
  recordId.value = route.query.recordId
  checkLoginStatus()
  checkAdClickStatus()
  
  if (!recordId.value) {
    ElMessage.error('测试记录ID不存在')
    router.push('/mbti')
    return
  }
  
  getResult()
  
  // 如果用户还没有点击过广告，则加载腾讯广告
  if (!hasClickedAd.value) {
    loadTencentAd()
  }
})

// 方法
const checkLoginStatus = () => {
  isLoggedIn.value = userStore.token !== undefined && userStore.token !== ''
}

const getResult = async () => {
  try {
    const response = await getTestResult(recordId.value)
    result.value = response.data
  } catch (error) {
    ElMessage.error('获取测试结果失败')
  } finally {
    loading.value = false
  }
}

const formatText = (text) => {
  if (!text) return ''
  // 将换行符转换为 <br>，将列表项转换为 <li>
  return text
    .replace(/\n/g, '<br>')
    .replace(/^\d+\.\s/gm, '<li>')
    .replace(/^-\s/gm, '<li>')
    .replace(/<li>/g, '<li style="margin-bottom: 8px;">')
}

const shareResult = () => {
  const shareText = `我的MBTI人格类型是 ${result.value.personalityType} - ${result.value.typeName}`
  
  if (navigator.share) {
    navigator.share({
      title: 'MBTI测试结果',
      text: shareText,
      url: window.location.href
    })
  } else {
    // 复制到剪贴板
    navigator.clipboard.writeText(shareText + ' ' + window.location.href).then(() => {
      ElMessage.success('结果已复制到剪贴板')
    })
  }
}

const downloadResult = () => {
  // 这里可以实现PDF下载功能
  ElMessage.info('下载功能开发中...')
}

const retakeTest = () => {
  router.push('/mbti')
}

const goHome = () => {
  router.push('/mbti')
}

const viewHistory = () => {
  router.push('/mbti')
}

const goToLoginWithSave = () => {
  // 检查是否已点击广告
  if (!hasClickedAd.value) {
    ElMessage.warning('请先点击广告支持我们，然后才能保存测试结果')
    return
  }
  
  // 保存当前测试结果到localStorage
  const saveData = {
    recordId: recordId.value,
    result: result.value,
    timestamp: new Date().toISOString(),
    action: 'save_result',
    adClicked: true
  }
  localStorage.setItem('mbtiResultToSave', JSON.stringify(saveData))
  
  // 跳转到登录页面
  router.push({
    path: '/login',
    query: { redirect: '/mbti/result', recordId: recordId.value }
  })
}

const dismissSavePrompt = () => {
  // 可以隐藏提示或者什么都不做
  ElMessage.info('您可以随时通过登录保存测试结果')
}

// 腾讯广告相关方法
const checkAdClickStatus = () => {
  hasClickedAd.value = checkAdStatus()
}

const loadTencentAd = () => {
  // 等待DOM元素准备好
  setTimeout(() => {
    const container = document.getElementById('tencent-ad-container')
    if (!container) {
      console.warn('广告容器元素未找到，延迟重试')
      setTimeout(loadTencentAd, 1000)
      return
    }
    
    // 由于腾讯广告SDK可能不可用，直接显示备用广告
    console.log('使用备用广告方案')
    showFallbackAd()
  }, 500)
}

const initTencentAd = () => {
  // 简化实现，直接使用备用广告
  console.log('初始化广告展示')
  showFallbackAd()
}

const showFallbackAd = () => {
  // 显示备用广告内容
  setTimeout(() => {
    const container = document.getElementById('tencent-ad-container')
    if (container) {
      container.innerHTML = `
        <div class="fallback-ad">
          <div class="ad-banner">
            <h4>🎯 推荐内容</h4>
            <p>发现更多有趣的心理测试和个人成长内容</p>
            <div class="ad-image">
              <div style="width: 100%; height: 120px; background: linear-gradient(45deg, #409EFF, #67C23A); border-radius: 8px; display: flex; align-items: center; justify-content: center; color: white; font-size: 18px;">
                📊 个人成长测评平台
              </div>
            </div>
            <p class="ad-cta">点击了解更多个性化测试</p>
          </div>
        </div>
      `
      adLoaded.value = true
      console.log('备用广告加载完成')
    } else {
      console.warn('广告容器未找到')
      adLoaded.value = true
    }
  }, 100)
}

const handleAdClick = () => {
  if (!adLoaded.value) {
    ElMessage.warning('广告还在加载中，请稍候...')
    return
  }
  
  // 直接处理广告点击
  handleAdRealClick()
}

const handleAdRealClick = () => {
  // 记录广告点击
  const clickData = saveAdClickRecord(recordId.value)
  hasClickedAd.value = true
  
  ElMessage.success('感谢您的支持！现在可以保存测试结果了')
  
  // 上报广告点击事件
  reportAdClick(clickData).catch(error => {
    console.log('广告点击统计上报失败:', error)
  })
}
</script>

<style lang="scss" scoped>
.loading-container {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.result-container {
  max-width: 1000px;
  margin: 0 auto;
}

.result-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 20px;
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
  color: white;
  border-radius: 12px;
  
  .personality-type {
    font-size: 4em;
    font-weight: bold;
    margin: 0 0 10px 0;
    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
  }
  
  .type-name {
    font-size: 2em;
    margin: 0 0 10px 0;
    font-weight: 300;
  }
  
  .type-nickname {
    font-size: 1.2em;
    margin: 0 0 30px 0;
    opacity: 0.9;
  }
  
  .share-buttons {
    .el-button {
      margin: 0 5px;
    }
  }
}

.description-section,
.scores-section,
.strengths-section,
.weaknesses-section,
.career-section,
.relationship-section,
.famous-people-section,
.percentage-section {
  margin-bottom: 30px;
  
  .el-card {
    :deep(.el-card__header) {
      background: #f8f9fa;
      
      h3 {
        margin: 0;
        color: #333;
        display: flex;
        align-items: center;
        
        .el-icon {
          margin-right: 8px;
          color: #409EFF;
        }
      }
    }
  }
}

.description-text {
  font-size: 16px;
  line-height: 1.8;
  color: #666;
  text-align: center;
  margin: 0;
}

.dimension-score {
  text-align: center;
  margin-bottom: 20px;
  
  .dimension-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    
    .dimension-name {
      font-weight: bold;
      color: #333;
    }
    
    .dimension-percentage {
      color: #409EFF;
      font-weight: bold;
    }
  }
  
  .dimension-description {
    margin-top: 10px;
    font-size: 14px;
    color: #666;
  }
}

.content-text {
  font-size: 15px;
  line-height: 1.8;
  color: #666;
  
  :deep(li) {
    list-style: none;
    position: relative;
    padding-left: 20px;
    
    &:before {
      content: "•";
      color: #409EFF;
      font-weight: bold;
      position: absolute;
      left: 0;
    }
  }
}

.percentage-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 40px;
  
  .percentage-chart {
    flex-shrink: 0;
  }
  
  .percentage-text {
    p {
      font-size: 16px;
      line-height: 1.6;
      color: #666;
      margin: 10px 0;
      
      strong {
        color: #409EFF;
        font-size: 18px;
      }
    }
  }
}

.tencent-ad-section {
  margin-bottom: 40px;
  
  .el-card {
    :deep(.el-card__header) {
      background: linear-gradient(135deg, #ff6b6b 0%, #ffa500 100%);
      color: white;
      
      h3 {
        margin: 0;
        color: white;
        display: flex;
        align-items: center;
        
        .el-icon {
          margin-right: 8px;
          color: white;
        }
      }
    }
  }
  
  .ad-content {
    text-align: center;
    
    .ad-description {
      margin-bottom: 20px;
      
      p {
        font-size: 16px;
        color: #333;
        margin: 10px 0;
        
        &.ad-hint {
          font-size: 14px;
          color: #666;
          font-style: italic;
        }
      }
    }
    
    .tencent-ad-container {
      margin: 20px 0;
      min-height: 150px;
      border: 2px dashed #e0e0e0;
      border-radius: 8px;
      padding: 20px;
      background: #fafafa;
      
      .ad-placeholder {
        .loading-text {
          margin-top: 15px;
          color: #666;
          font-size: 14px;
        }
      }
      
      .fallback-ad {
        .ad-banner {
          h4 {
            color: #409EFF;
            margin-bottom: 10px;
            font-size: 18px;
          }
          
          p {
            color: #666;
            margin: 8px 0;
            
            &.ad-cta {
              color: #409EFF;
              font-weight: bold;
              margin-top: 15px;
            }
          }
          
          .ad-image {
            margin: 15px 0;
          }
        }
      }
    }
    
    .ad-actions {
      margin-top: 20px;
      
      .el-button {
        font-size: 16px;
        padding: 12px 30px;
        
        &:disabled {
          opacity: 0.6;
        }
      }
    }
  }
}

.login-save-section {
  margin-bottom: 40px;
  
  .alert-actions {
    margin-top: 15px;
    display: flex;
    gap: 10px;
    
    .el-button {
      flex: 1;
    }
  }
  
  :deep(.el-alert) {
    .el-alert__content {
      .el-alert__description {
        margin-bottom: 0;
      }
    }
  }
}

.action-section {
  text-align: center;
  margin: 50px 0;
  
  .el-button {
    margin: 0 10px 10px 10px;
  }
}

.error-container {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media (max-width: 768px) {
  .result-header {
    .personality-type {
      font-size: 3em;
    }
    
    .type-name {
      font-size: 1.5em;
    }
  }
  
  .percentage-content {
    flex-direction: column;
    gap: 20px;
  }
}
</style>
